<template>
  <teleport :to="teleportTarget">
    <slot name="content"></slot>
  </teleport>
</template>

<script setup lang="ts">
import {
  computed,
  defineProps,
  nextTick,
  onBeforeMount,
  onUnmounted,
  ref,
} from "vue";
import { onRevalidateTeleportTarget } from "./status";
import { store } from "./store";

const props = defineProps({
  teleportTarget: { type: String, required: true },
});
const disabled = ref(true);


// 这个定时器的作用是兜底，如果无法跟踪状态，就定时刷新。
const layoutContentTimer = window.setInterval(async () => {
  if ("#" + props.teleportTarget !== teleportTarget.value) {
    const teleportTargetExist =
      document.querySelector("#" + props.teleportTarget) != null;
    if (teleportTargetExist) {
      store.state.hiddenTargets.delete(props.teleportTarget)
      revalidate();
    }
  }
}, 1000);

const teleportTarget = computed(() => {
  return store.state.hiddenTargets.has(props.teleportTarget)
    ? "#empty-slot"
    : "#" + props.teleportTarget;
});
const revalidate = async () => {
  try {
    store.commit('hideTarget', props.teleportTarget)
    await nextTick();
  } catch (e) {
    console.log(e);
  }
  store.state.hiddenTargets.delete(props.teleportTarget);
  await nextTick();
};
// 重置要传送到的对象。
// 先将传送目标设置到空div试着挂载一下，然后退出，尝试挂到新的div。
onRevalidateTeleportTarget(async (targetID: string) => {
  console.log("request revalidate target!", targetID);
  if (targetID != props.teleportTarget) {
    return;
  }
  await revalidate();
});

onBeforeMount(() => {
  if (document.getElementById(props.teleportTarget) == null) {
    store.commit('hideTarget', props.teleportTarget)
  }
});

onUnmounted(() => {
  console.log("unmounted");
});
</script>

<style></style>
